package com.atguigu.paymentdemo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.paymentdemo.entity.CatOutEntity;
import com.atguigu.paymentdemo.entity.OrderInfo;
import com.atguigu.paymentdemo.entity.Product;
import com.atguigu.paymentdemo.enums.OrderStatus;
import com.atguigu.paymentdemo.mapper.OrderInfoMapper;
import com.atguigu.paymentdemo.mapper.ProductMapper;
import com.atguigu.paymentdemo.service.OrderInfoService;
import com.atguigu.paymentdemo.util.OrderNoUtils;
import com.atguigu.paymentdemo.util.PhoneRechargeCheckUtil;
import com.atguigu.paymentdemo.util.PhoneRechargeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Resource
    private ProductMapper productMapper;

@Autowired
private OrderInfoMapper orderInfoMapper;

    /*@Resource
    private OrderInfoMapper orderInfoMapper;*/

    @Override
    public OrderInfo createOrderByProductId(Long productId, String paymentType) {

        //查找已存在但未支付的订单
        OrderInfo orderInfo = this.getNoPayOrderByProductId(productId, paymentType);
        if( orderInfo != null){
            return orderInfo;
        }

        //获取商品信息
        Product product = productMapper.selectById(productId);

        //生成订单
        orderInfo = new OrderInfo();
        orderInfo.setTitle(product.getTitle());
        orderInfo.setOrderNo(OrderNoUtils.getOrderNo()); //订单号
        orderInfo.setProductId(productId);
        orderInfo.setTotalFee(product.getPrice()); //分
        orderInfo.setOrderStatus(OrderStatus.NOTPAY.getType()); //未支付
        orderInfo.setPaymentType(paymentType);
        baseMapper.insert(orderInfo);

        return orderInfo;
    }
    @Override
    public OrderInfo createOrderByProductId2(Long productId, String paymentType, CatOutEntity catOutEntity) {

        //查找已存在但未支付的订单
//        OrderInfo orderInfo = this.getNoPayOrderByProductId2(productId, paymentType,catOutEntity);
//        if( orderInfo != null){
//            return orderInfo;
//        }
        OrderInfo orderInfo = new OrderInfo();
        //获取商品信息
        Product product = productMapper.selectById(productId);

        //生成订单
        orderInfo = new OrderInfo();
        orderInfo.setTitle(product.getTitle());
        if(productId==5L){
            //100话费
            orderInfo.setOrderNo("HF"+OrderNoUtils.getOrderNo()); //订单号

        }else if(productId==12345L){
            //权益卡
            orderInfo.setOrderNo("QYC"+OrderNoUtils.getOrderNo()); //订单号

        }else if(productId==6L){
            //抵扣卷
            orderInfo.setOrderNo("DKJ"+OrderNoUtils.getOrderNo()); //订单号

        }
        orderInfo.setProductId(productId);
        orderInfo.setTotalFee(product.getPrice()); //分
        orderInfo.setOrderStatus(OrderStatus.NOTPAY.getType()); //未支付
        orderInfo.setPaymentType(paymentType);
        orderInfo.setBxmId(catOutEntity.getBxm_id());
        orderInfo.setPhone(catOutEntity.getPhone());
        baseMapper.insert(orderInfo);

        return orderInfo;
    }

    /**
     * 存储订单二维码
     * @param orderNo
     * @param codeUrl
     */
    @Override
    public void saveCodeUrl(String orderNo, String codeUrl) {

        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);

        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setCodeUrl(codeUrl);

        baseMapper.update(orderInfo, queryWrapper);
    }

    /**
     * 查询订单列表，并倒序查询
     * @return
     */
    @Override
    public List<OrderInfo> listOrderByCreateTimeDesc() {

        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<OrderInfo>().orderByDesc("create_time");
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 根据订单号更新订单状态,保存权益卡信息 ，请求充值中心
     * @param orderNo
     * @param orderStatus
     */
    @Override
    public void updateStatusByOrderNo(String orderNo, OrderStatus orderStatus) {

        String czType="100"; //充值类型 10为10元,100 为100元
        log.info("更新订单状态 ===> {}", orderStatus.getType());

        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);

        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderStatus(orderStatus.getType());

        baseMapper.update(orderInfo, queryWrapper);
        //根据订单号查询订单信息
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        OrderInfo o1=baseMapper.selectOne(queryWrapper);
        if(o1.getProductId()==12345L){
            log.info("订单信息为:{} ===> {}", JSONObject.toJSONString(o1));

            CatOutEntity catOutEntity=new CatOutEntity();
            catOutEntity.setBxm_id(o1.getBxmId());
            catOutEntity.setPhone(o1.getPhone());
            catOutEntity.setNum(1);
            catOutEntity.setStatus("1"); //1可用，0不可用
            catOutEntity.setId(IdWorker.getId());
            catOutEntity.setCreateTime(new Date());
            catOutEntity.setUpdateTime(new Date());
            orderInfoMapper.saveCatOut(catOutEntity);
            log.info("新增权益卡记录:{}", JSONObject.toJSONString(catOutEntity));

        }else if(o1.getProductId()==5L){
            log.info("订单信息为:{} ===> {}", JSONObject.toJSONString(o1));
            //3. 查询是否可以充值
            if(!o1.getOrderStatus().equals("支付成功")){
                log.error("订单状态不正确");
                throw new RuntimeException("订单状态不正确");
            }
//            log.info("2.查询是否可以充值 ===> {}", bxm_id);
            //1.检查订单状态

            try {
                String phoneStatus= PhoneRechargeCheckUtil.telcheck(o1.getPhone(),czType);
                log.info("充值中心返回检测信息:{}", phoneStatus);
                String rechargeInfo=PhoneRechargeUtil.recharge(o1.getPhone(),czType,o1.getOrderNo());
                log.info("充值中心返回充值结果信息:{}", rechargeInfo);
            } catch (IOException e) {
                log.error("充值中心请求失败:{}",e);
                throw new RuntimeException(e);
            }


        }

        //1.根据订单号前缀为QYC的新增t_cat_out表 权益卡表

        //2.根据订单号前缀为HF的,向充值中心请求充100元话费

    }

    /**
     * 根据订单号获取订单状态
     * @param orderNo
     * @return
     */
    @Override
    public String getOrderStatus(String orderNo) {

        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        OrderInfo orderInfo = baseMapper.selectOne(queryWrapper);
        if(orderInfo == null){
            return null;
        }
        return orderInfo.getOrderStatus();
    }

    /**
     * 查询创建超过minutes分钟并且未支付的订单
     * @param minutes
     * @return
     */
    @Override
    public List<OrderInfo> getNoPayOrderByDuration(int minutes, String paymentType) {

        Instant instant = Instant.now().minus(Duration.ofMinutes(minutes));

        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_status", OrderStatus.NOTPAY.getType());
        queryWrapper.le("create_time", instant);
        queryWrapper.eq("payment_type", paymentType);

        List<OrderInfo> orderInfoList = baseMapper.selectList(queryWrapper);

        return orderInfoList;
    }

    /**
     * 根据订单号获取订单
     * @param orderNo
     * @return
     */
    @Override
    public OrderInfo getOrderByOrderNo(String orderNo) {

        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        OrderInfo orderInfo = baseMapper.selectOne(queryWrapper);

        return orderInfo;
    }


    /**
     * 根据商品id查询未支付订单
     * 防止重复创建订单对象
     * @param productId
     * @return
     */
    private OrderInfo getNoPayOrderByProductId(Long productId, String paymentType) {

        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", productId);
        queryWrapper.eq("order_status", OrderStatus.NOTPAY.getType());
        queryWrapper.eq("payment_type", paymentType);
//        queryWrapper.eq("user_id", userId);
        OrderInfo orderInfo = baseMapper.selectOne(queryWrapper);
        return orderInfo;
    }
    private OrderInfo getNoPayOrderByProductId2(Long productId, String paymentType,CatOutEntity catOutEntity) {

        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", productId);
        queryWrapper.eq("order_status", OrderStatus.NOTPAY.getType());
        queryWrapper.eq("payment_type", paymentType);
        queryWrapper.eq("phone", catOutEntity.getPhone());

//        queryWrapper.eq("user_id", userId);
        OrderInfo orderInfo = baseMapper.selectOne(queryWrapper);
        return orderInfo;
    }

}
